package com.h.trans.controller;

import com.h.trans.service.UserService;
import jakarta.annotation.sql.DataSourceDefinition;
import jakarta.annotation.sql.DataSourceDefinitions;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Spring 编程式事务
 */
@Slf4j
@RequestMapping("/user")
@RestController
public class UserController {
    @Autowired
    private UserService userService;
    // JDBC事务管理器
    @Autowired
    private DataSourceTransactionManager dataSourceTransactionManager;
    // 定义事务属性
    @Autowired
    private TransactionDefinition definitions;

    @RequestMapping("/registry")
    public String registry(String name,String password) {
        /**
         * 1. 开启事务
         * 2. 数据操作
         * 3. 事务提交/回滚
         */
        //开启事务
        TransactionStatus transaction = dataSourceTransactionManager.getTransaction(definitions);

        // 数据操作
        userService.registryUser(name,password);
        log.info("用户注册成功");

//        //事务提交
//        dataSourceTransactionManager.commit(transaction);

        // 事务回滚
        dataSourceTransactionManager.rollback(transaction);
        return "注册成功";
    }
}
